<?php

/**
 * Write PHP array to file
 *
 * @package Rapide_Util
 *
 */
class Rapide_Util_Array2File
{
	/**
	 * Save array to file
	 *
	 * @param array $aArray
	 * @param string $sName array name in file
	 * @param string $sFilename
	 */
	public function save(array $aArray, $sName, $sFilename)
	{
		$sString	= "<?php\n";
		$sString .= '$' . $sName . ' = array(' . $this->_array2String($aArray) . ');' . "\n";
		$sString .= "?>\n";

		file_put_contents($sFilename, $sString);
	}

	private function _array2String(array $aArray)
	{
		$sArray = '';

		foreach($aArray as $key => $value)
		{
			$sArray .= $this->_key($key) . ' => ' . $this->_value($value) . ", ";
		}

		return substr($sArray, 0, -2);
	}

	private function _key($mKey)
	{
		return is_int($mKey) ? $mKey : "'$mKey'";
	}

	private function _value($mValue)
	{
		if(is_numeric($mValue))
		{
			return $mValue;
		}
		elseif(is_bool($mValue))
		{
			return $mValue ? 'true' : 'false';
		}
		elseif(is_string($mValue))
		{
			$sValue = str_replace("'", "\'", $mValue);
			return "'$sValue'";
		}
		elseif(is_array($mValue))
		{
			$sArray	= 'array(' . $this->_array2String($mValue). ')';
			return $sArray;
		}
		else
			return 'null';
	}
}

?>
